﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Icoders.MarketTracker.Web.Lib.Command;
using Icoders.MarketTracker.Web.Lib.Command.Bus;
using Icoders.MarketTracker.Web.Lib.Command.Helper;
using Icoders.MarketTracker.Web.Lib.Response.Containers;
using log4net;

namespace Icoders.MarketTracker.Web.Controllers
{
    public class SyncUpTransactionDataController : Controller
    {
        //
        // GET: /SyncUpTransactionData/
        ILog _log = LogManager.GetLogger("CommandController");
        ICommandDeserialize _commandDeserialize;
        IBusPublisher _busPublisher;

        public SyncUpTransactionDataController(ICommandDeserialize commandDeserialize, IBusPublisher busPublisher)
        {
            _commandDeserialize = commandDeserialize;
            _busPublisher = busPublisher;
        }

        [HttpPost]
        public JsonResult Process(string commandType, string jsoncommand, string sendDateTime)
        {
            string result = "";
            string errorInfo = "";
            _log.InfoFormat("Processing command : {0} with {1} ", commandType, jsoncommand);
            try
            {
                DateTime _sendDateTime = _commandDeserialize.DeserializeSendDateTime(sendDateTime);
                ICommand deserializedCommand = _commandDeserialize.DeserializeCommand(commandType, jsoncommand);
                bool isValid = deserializedCommand != null;
                result = isValid ? "OK" : "Invalid";
                deserializedCommand.CmdSendDateTime = _sendDateTime;
                _log.InfoFormat("Deserialization is valid " + result);
                errorInfo = isValid ? "" : "Failed to deserialize " + commandType;
                if (isValid)
                {
                    _log.Info("Client SendDateTime " + sendDateTime);
                    _log.Info("Placed on bus");
                    _log.Info("Command ID " + deserializedCommand);
                    _busPublisher.Publish(deserializedCommand);

                }
                else
                    _log.Error("Failed to deserialize " + commandType);
            }
            catch (Exception ex)
            {
                result = "Invalid";
                _log.ErrorFormat("ERROR Processing command : {0} ", commandType);
                _log.Error(ex);
            }
            ResponseBasic response = new ResponseBasic {Result = result, ErrorInfo = errorInfo};
            _log.Info("Final response " + response.Result);
            return Json(response);
        }

    }
}
